package sg.edu.nus.iss.vmcs.system;

import java.io.IOException;

import sg.edu.nus.iss.vmcs.abstraction.DataStoreLoaderFactory;
import sg.edu.nus.iss.vmcs.abstraction.IStoreFactory;
import sg.edu.nus.iss.vmcs.store.CashStore;
import sg.edu.nus.iss.vmcs.store.CashStoreItem;
import sg.edu.nus.iss.vmcs.store.DrinksStore;
import sg.edu.nus.iss.vmcs.store.DrinksStoreItem;
import sg.edu.nus.iss.vmcs.store.Store;
import sg.edu.nus.iss.vmcs.store.StoreObject;
import sg.edu.nus.iss.vmcs.util.VMCSException;

/*
 * @author Mon Ye Thant
 */

public class StoreFactory implements IStoreFactory
{
	CashDataLoader cashLoader;
	DrinkDataLoader drinksLoader;
	
	public StoreFactory(DataStoreLoaderFactory dataStoreLoaderFactory) throws IOException
	{		
		cashLoader = dataStoreLoaderFactory.createCashDataLoader();
		drinksLoader = dataStoreLoaderFactory.createDrinkDataLoader();
	}

	@Override
	public Store createStore(int type) throws VMCSException
	{
		switch (type)
		{
		case Store.CASH:
			return createCashStore();
		case Store.DRINK:
			return createDrinksStore();
		default:
			return null;
		}
	}

	private Store createCashStore() throws VMCSException
	{
		int numOfItems = cashLoader.getNumOfItems();

		CashStore cashStore = new CashStore();
		cashStore.setPropertyLoader(cashLoader);
		cashStore.setStoreSize(numOfItems);

		for (int i = 0; i < numOfItems; i++)
		{
			CashStoreItem item = (CashStoreItem) cashLoader.getItem(i);
			cashStore.addItem(i, item);
		}

		return cashStore;
	}

	private Store createDrinksStore() throws VMCSException
	{
		int numOfItems = drinksLoader.getNumOfItems();

		DrinksStore drinkStore = new DrinksStore();
		drinkStore.setPropertyLoader(drinksLoader);
		drinkStore.setStoreSize(numOfItems);

		for (int i = 0; i < numOfItems; i++)
		{
			DrinksStoreItem item = (DrinksStoreItem) drinksLoader
					.getItem(i);
			StoreObject brand = item.getContent();
			StoreObject existingBrand = drinkStore.findObject(brand
					.getName());
			if (existingBrand != null)
			{
				item.setContent(existingBrand);
			}
			drinkStore.addItem(i, item);
		}

		return drinkStore;
	}
}
